import path from 'node:path'
import { defineConfig } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueJsx from '@vitejs/plugin-vue-jsx'
import vueDevTools from 'vite-plugin-vue-devtools'
import tailwindcss from '@tailwindcss/vite'
import type {
  AssistantStepType,
  OriginAssistantType,
  Platform,
} from './src/type'
import { config } from 'node:process'
import fs from 'node:fs'
import { globSync } from 'glob'
import { Marked } from 'marked'

async function generateConfigFromPublic() {
  const metaConfig: { [key: string]: OriginAssistantType } = {}
  globSync('./public/*/meta.json').forEach((file) => {
    let meta = {} as OriginAssistantType
    const basePath = path.dirname(file)
    const trimedBasePath = basePath.replace('public/', '')
    const key = path.basename(basePath)
    console.log(basePath, key)
    const content = fs.readFileSync(file, 'utf-8')

    // 获取封面数据
    const thumbnails = fs.readdirSync(path.join(basePath, 'thumbnail'))

    let thumbs = {}
    thumbnails.forEach((thumb) => {
      if (thumb.startsWith('pc.')) {
        thumbs = {
          ...thumbs,
          pc: path.join(trimedBasePath, 'thumbnail', thumb),
        }
      }
      if (thumb.startsWith('mobile.')) {
        thumbs = {
          ...thumbs,
          mobile: path.join(trimedBasePath, 'thumbnail', thumb),
        }
      }
    })

    meta = {
      ...JSON.parse(content),
      tableList: {},
      thumbnail: thumbs,
    }
    fs.readdirSync(basePath).forEach((platform) => {
      if (platform.endsWith('.json')) {
        return
      }
      const allSteps = fs.readdirSync(path.join(basePath, platform))
      //
      // switch (platform) {
      //   case 'pc':
      //     meta

      // meta.tableList.PC = []
      //
      const steps: AssistantStepType[] = []

      allSteps.forEach((step) => {
        if (step.endsWith('.md')) {
          const fileName = path.basename(step, '.md')
          const imgfileNames = allSteps.filter(
            (s) => s.startsWith(fileName) && !s.endsWith('.md'),
          )
          // console.log(fileName, imgfileNames)
          if (imgfileNames.length == 1) {
            steps.push({
              media: path.join(trimedBasePath, platform, imgfileNames[0]),
              article: path.join(trimedBasePath, platform, step),
            })
          }
        }
      })
      if (steps.length > 0) {
        meta.tableList[platform as Platform] = steps
      }

      metaConfig[key] = meta
    })

    // console.log(JSON.stringify(metaConfig, null, 2))
  })
  fs.writeFileSync('./src/articles.json', JSON.stringify(metaConfig, null, 2))
  fs.cpSync('./src/config.json', './public/config.json')
}

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
  console.log(mode)
  return {
    plugins: [
      vue(),
      vueJsx(),
      tailwindcss(),
      {
        name: 'generate-articles-map',
        buildStart: generateConfigFromPublic,
      },
    ],
    base: mode == 'production' ? '/_modules/assistant/' : '/',
    resolve: {
      alias: {
        '@': path.resolve(__dirname, './src'),
      },
    },
    server: {
      allowedHosts: true,
    },
  }
})
